// 事件处理模块 - 负责处理用户交互
import { getUIElements } from './ui.js';
import { handleImage } from './ocr.js';
import { dragElement } from './utils.js';
import { saveRecords } from './data.js';

// 添加一个状态变量来跟踪是否正在进行OCR识别
let isProcessing = false;

export function setupEventListeners(records, saveRecords, addRecordToUI) {
  const { btn, modal, uploadArea, recordsContainer } = getUIElements();
  
  // 按钮点击事件
  btn.addEventListener('click', () => {
    // 计算弹窗位置
    const btnRect = btn.getBoundingClientRect();
    const modalWidth = 350; // 弹窗宽度
    const modalHeight = 600; // 弹窗高度
    const gap = 10; // 按钮和弹窗之间的间距
    const boundaryGap = 20; // 与边界之间的间隙
    
    // 计算弹窗的left位置，使弹窗水平居中对齐按钮
    let modalLeft = btnRect.left + btnRect.width / 2 - modalWidth / 2;
    
    // 确保弹窗不会超出屏幕左侧边界，留出20px间隙
    if (modalLeft < boundaryGap) {
      modalLeft = boundaryGap;
    }
    
    // 确保弹窗不会超出屏幕右侧边界，留出20px间隙
    const maxLeft = window.innerWidth - modalWidth - boundaryGap;
    if (modalLeft > maxLeft) {
      modalLeft = maxLeft;
    }
    
    // 检查上方是否有足够空间显示弹窗
    const spaceAbove = btnRect.top - boundaryGap;
    const spaceBelow = window.innerHeight - btnRect.bottom - boundaryGap;
    
    let modalBottom;
    
    // 如果上方空间足够显示弹窗，或者上方空间比下方空间大，则在上方显示
    if (spaceAbove >= modalHeight || spaceAbove >= spaceBelow) {
      // 弹窗出现在按钮正上方
      modalBottom = window.innerHeight - btnRect.top + gap;
      
      // 确保弹窗不会超出屏幕上边界，留出20px间隙
      const maxBottom = window.innerHeight - modalHeight - boundaryGap;
      if (modalBottom > maxBottom) {
        modalBottom = maxBottom;
      }
    } else {
      // 弹窗出现在按钮正下方
      modalBottom = window.innerHeight - btnRect.bottom - modalHeight - gap;
      
      // 确保弹窗不会超出屏幕下边界，留出20px间隙
      if (modalBottom < boundaryGap) {
        modalBottom = boundaryGap;
      }
    }
    
    // 应用计算后的位置
    modal.style.left = modalLeft + 'px';
    modal.style.bottom = modalBottom + 'px';
    
    // 切换弹窗显示状态
    modal.style.display = modal.style.display === 'flex' ? 'none' : 'flex';
  });

  modal.querySelector('.modal-close').addEventListener('click', () => {
    modal.style.display = 'none';
  });

  // 上传区点击
  uploadArea.addEventListener('click', () => {
    // 如果正在处理中，则不响应点击
    if (isProcessing) return;
    
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = (e) => {
      if (e.target.files[0]) {
        isProcessing = true;
        handleImage(e.target.files[0], records, saveRecords, addRecordToUI)
          .finally(() => {
            isProcessing = false;
          });
      }
    };
    input.click();
  });

  // 拖拽事件处理
  ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
    uploadArea.addEventListener(eventName, e => {
      e.preventDefault();
      e.stopPropagation();
    }, false);
  });

  ['dragenter', 'dragover'].forEach(eventName => {
    uploadArea.addEventListener(eventName, () => {
      // 如果正在处理中，则不显示高亮效果
      if (isProcessing) return;
      uploadArea.classList.add('highlight');
    });
  });

  ['dragleave', 'drop'].forEach(eventName => {
    uploadArea.addEventListener(eventName, () => {
      uploadArea.classList.remove('highlight');
    });
  });

  uploadArea.addEventListener('drop', (e) => {
    // 如果正在处理中，则不响应拖拽
    if (isProcessing) return;
    
    const files = e.dataTransfer.files;
    const items = e.dataTransfer.items;
    
    // 处理文件拖拽
    if (files.length > 0) {
      const file = files[0];
      if (file && file.type.startsWith('image/')) {
        isProcessing = true;
        handleImage(file, records, saveRecords, addRecordToUI)
          .finally(() => {
            isProcessing = false;
          });
      }
      return;
    }
    
    // 处理网页图片拖拽
    if (items) {
      for (let i = 0; i < items.length; i++) {
        // 检查是否为文件类型
        if (items[i].kind === 'file') {
          const file = items[i].getAsFile();
          if (file && file.type.startsWith('image/')) {
            isProcessing = true;
            handleImage(file, records, saveRecords, addRecordToUI)
              .finally(() => {
                isProcessing = false;
              });
            return;
          }
        }
        // 检查是否为URL类型（网页图片）
        else if (items[i].kind === 'string' && items[i].type === 'text/uri-list') {
          items[i].getAsString((url) => {
            // 检查是否为图片URL
            if (url && (url.match(/\.(jpeg|jpg|gif|png|webp|bmp)/i) || 
                       url.includes('data:image'))) {
              // 创建图片对象来获取图片数据
              const img = new Image();
              img.crossOrigin = 'Anonymous';
              img.onload = function() {
                // 将图片转换为Blob
                const canvas = document.createElement('canvas');
                canvas.width = this.width;
                canvas.height = this.height;
                const ctx = canvas.getContext('2d');
                ctx.drawImage(this, 0, 0);
                
                canvas.toBlob((blob) => {
                  if (blob) {
                    // 创建一个新的File对象
                    const file = new File([blob], 'dragged-image.png', {type: 'image/png'});
                    isProcessing = true;
                    handleImage(file, records, saveRecords, addRecordToUI)
                      .finally(() => {
                        isProcessing = false;
                      });
                  }
                }, 'image/png');
              };
              img.onerror = function() {
                console.error('无法加载拖拽的图片');
              };
              img.src = url;
            }
          });
          return;
        }
      }
    }
  });

  // 粘贴（Ctrl+V）
  document.addEventListener('paste', (e) => {
    if (modal.style.display !== 'flex') return;
    // 如果正在处理中，则不响应粘贴
    if (isProcessing) return;
    
    const item = e.clipboardData.items[0];
    if (item.type.indexOf('image') !== -1) {
      const blob = item.getAsFile();
      isProcessing = true;
      handleImage(blob, records, saveRecords, addRecordToUI)
        .finally(() => {
          isProcessing = false;
        });
    }
  });

  // 弹窗拖拽
  dragElement(modal);
}